package Hot100;

import java.util.HashMap;
import java.util.Map;

public class 和为K的子数组 {
    public int subarraySum(int[] nums, int k) {
        // key：前缀和，value：key对应的前缀和的个数
        Map<Integer, Integer> preSumFreq = new HashMap<>();
        // 对于下标为 0 的元素，前缀和为 0，个数为 1
        preSumFreq.put(0, 1);
        int count = 0;
        int preSum = 0;
        for (int num : nums) {
            preSum += num;
            count += preSumFreq.getOrDefault(preSum - k, 0);
            preSumFreq.put(preSum, preSumFreq.getOrDefault(preSum, 0) + 1);
        }
        return count;
    }
}
